<?php

abstract class baseWemTask extends sfBaseTask
{
    
    private $fileLogger;
    private $databaseManager;
    private $dbConnection;
    private $commandManager;
    
    public function configure()
    {
        
        $this->namespace = 'wem';
        $this->cazzo="figa";
        //OPTIONS
        $this->addOptions(array(
            new sfCommandOption('application', null,sfCommandOption::PARAMETER_REQUIRED, 'The application name', 'backend'),
            new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED,'The environment', 'dev'), 
            new sfCommandOption('debug', null, sfCommandOption::PARAMETER_NONE,'Enable/Disable Error Reporting'),
            ));
 
        //ARGUMENTS
    }
    
    protected function addFileLogger($plantname="")
    {
	 
      if ( count($this->dispatcher->getListeners('command.log'))<2){
          
        //CREATE DIRECTORY
        $path=$this->configuration->getRootDir()."/log";
        if ($plantname!="")
            $path=$path."/".$plantname;
        if (!is_dir($path))
             $this->getFilesystem()->mkdirs ($path);
        
        //get or create log file
        $plantname=$plantname!=""?"_".$plantname:"";
        $logfile=$this->name.$plantname.".txt";  
        
        $logfilePath=$path."/".$logfile;
        
        if (is_file($logfilePath))
           $this->rotateLog($path, $logfile); 
        else
           $this->getFilesystem()->touch($logfilePath);
         
        //connect logging to log file
        $this->fileLogger = new sfFileLogger($this->dispatcher, array('file' => $logfilePath));
        $this->dispatcher->connect('command.log', array($this->fileLogger, 'listenToLogEvent'));

        //Manage error reporting
        $options=$this->commandManager->getOptionValues();
        if (!$options['debug'])
            error_reporting(E_ERROR | E_PARSE);
        else
            error_reporting (E_ALL);
      }
    }
    
    protected function rotateLog($path,$logfile){
            //LOG ROTATION
            //move in db file older than $d days. The back stores $n files
            //$d and $n are defined in config
            $logfilePath=$path."/".$logfile;
            
            //checks if history folder already exist, otherwise creates it
            $history=$path."/history";
            if (!is_dir($history))
                $this->getFilesystem()->mkdirs ($history);

            $d=sfConfig::get("app_log_rotate_days");
            $now=new DateTime();
            $rangeLimit=$now->sub(new DateInterval("P".$d."D"));

            // determine date of last rotation
	    $logs = sfFinder::type('file')->maxdepth(1)->name(str_replace(".txt", "_*.log", $logfile))->sort_by_name()->in($history);
	    $recentlog = is_array($logs) ? array_pop($logs) : null;      
            if ($recentlog){
              $lastRotatedOn=new DateTime();
			  $lastRotatedOn->setTimestamp(filemtime($recentlog)); 
            }else
	      // no rotation has occured yet
	      $lastRotatedOn = null;

            if ( !isset($lastRotatedOn) || $lastRotatedOn<=$rangeLimit){
                //copy the log file in history folder
                $mTime=new DateTime();
                $mTime->setTimestamp(filemtime($logfilePath));
                $buLogfile=str_replace(".txt", "_".$mTime->format("Ymd").".log", $logfile);
                $this->getFilesystem()->copy($logfilePath, $history."/".$buLogfile);

                if (is_file($history."/".$buLogfile)){
                    //remove the logfile
                    $this->getFilesystem()->remove($logfilePath);
                    //creates a new logfile
                    $this->getFilesystem()->touch($logfilePath);
                    
                    // if the number of log files in history exceeds $n then remove the oldest log
                    $logs = sfFinder::type('file')->maxdepth(1)->name(str_replace(".txt", "_*.log", $logfile))->sort_by_name()->in($history);
                    $n=sfConfig::get("app_log_rotate_bu");
                   while(count($logs)>$n){
                         $this->getFilesystem()->remove($logs[0]);
                         array_shift($logs);
                    }; 
                }
            }
            
    }

    protected function ConnectDB(){
        // connect to the environment database
        $this->databaseManager = new sfDatabaseManager($this->configuration);
        $this->dbConnection = $this->databaseManager->getDatabase('doctrine')->getConnection();
        $this->dbConnection->setAttribute(Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS, true );
    }
    
    protected function process(sfCommandManager $commandManager, $options) {
        parent::process($commandManager, $options);
        $this->commandManager=$commandManager;
    }       
}


?>

